package com.flushbonading.util;

import javax.servlet.http.HttpServletResponse;
import java.io.*;

/**
 * @author zyx 2134208960@qq.com
 * @version 0.1.0
 * @create 2021-03-15 09:33
 * @since 0.1.0
 **/
public class FileOptionUtils {
    public static boolean download(HttpServletResponse response, String responseFileName, String sourceFileName){

            response.setContentType("application/octet-stream;charset=utf-8");

            response.setHeader("Content-Disposition", "attachment; filename=" + responseFileName);
            byte[] buff = new byte[1024];
            //创建缓冲输入流
            BufferedInputStream bis = null;
            OutputStream outputStream = null;

            try {
                outputStream = response.getOutputStream();

                //这个路径为待下载文件的路径
                bis = new BufferedInputStream(new FileInputStream(new File(".\\" + sourceFileName)));
                int read = 0;
                try {
                    read = bis.read(buff);
                } catch (IOException e) {
                    e.printStackTrace();
                }

                //通过while循环写入到指定了的文件夹中
                while (read != -1) {
                    outputStream.write(buff, 0, buff.length);
                    //outputStream.flush();
                    read = bis.read(buff);
                }
            } catch ( IOException e ) {
                e.printStackTrace();
            } finally {
                if (bis != null) {
                    try {
                        bis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (outputStream != null) {
                    try {
                        outputStream.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }

        return false;
    }
}
